package cn.tedu;

import java.sql.*;
import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = sc.nextLine();
        System.out.println("请输入密码");
        String password = sc.nextLine();
        try (Connection conn = DBUtils.getConn()){
//            Statement s = conn.createStatement();
//            ResultSet rs = s.executeQuery("SELECT COUNT(*) FROM user WHERE username='"
//                    +username+"' AND password='"+password+"'");
//            通过PreparedStatement执行SQL语句
            String sql = "SELECT COUNT(*) FROM user WHERE username=? AND password=?";
            //预编译的SQL执行对象在这一步的时候就将SQL语句的业务部分锁死,之后替换换?时不管用户写的内容
            //是什么都以值的形式处理,这样就不会影响原有SQL语句的逻辑
            PreparedStatement ps = conn.prepareStatement(sql);
            //把?替换成变量
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet rs = ps.executeQuery();
            //取出结果集对象中查询到的数量
            rs.next();  //需要先让结果集的游标往下移动一格
            int count = rs.getInt(1);
            if (count>0){
                System.out.println("登录成功!");
            }else System.out.println("用户名或密码错误!");

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
//SELECT COUNT(*) FROM user WHERE username='abcd' AND password='' or '1'='1'